package com.hh.game.service.gateway.filter.request;

import com.google.common.collect.Maps;
import com.hh.game.service.gateway.codec.Request;
import com.hh.game.service.gateway.utils.IpUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public abstract class SynRequestFilter extends ChannelInboundHandlerAdapter {
    /** 路由：请求间隔*/
    private Map<String ,Long> routeConfig;
    /** 路由：最后一次请求时间*/
    private Map<String ,Long> routeCache;

    private Set<String> whiteIps;

    public SynRequestFilter(Map<String ,Long> routeConfig , Set<String> whiteIps) {
        this.routeConfig = routeConfig;
        this.routeCache = Maps.newHashMapWithExpectedSize(routeConfig.size());
        this.whiteIps = whiteIps == null ? new HashSet<>(0) : whiteIps;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof Request){
            Request request = (Request) msg;
            String route = request.getRoute();
            Long timer = routeConfig.get(route);
            if(timer != null){
                Long now = System.currentTimeMillis();
                Long interval = routeCache.get(route);
                if(interval != null && now - interval < timer){
                    String ip = IpUtil.getIp(ctx);
                    if(!whiteIps.contains(ip)){
                        noticeClientSynRequest(ctx);
                        return;
                    }
                }
                routeCache.put(route ,now);
            }
        }
        super.channelRead(ctx, msg);

    }

    protected abstract void noticeClientSynRequest(ChannelHandlerContext ctx);
}
